using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Text;

namespace BlogDemo.Infrastructure
{
    /// <summary>
    /// 用于 EF Core Migration 时创建 DbContext，数据库连接信息来自 BlogDemo.Api 项目 appsettings.json
    /// </summary>
    public class BlogDbContextDesignFactory : IDesignTimeDbContextFactory<BlogDbContext>
    {
        private const string DefaultConnectionStringName = "Sqlite";
        //////// 
        public BlogDbContext CreateDbContext(string[] args)
        {
            var builder = new DbContextOptionsBuilder<BlogDbContext>();

            string basePath = AppDomain.CurrentDomain.BaseDirectory;
            string envName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(basePath)
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{envName}.json", true)
                .Build();
            var connectionString = configuration.GetConnectionString(DefaultConnectionStringName);
            builder.UseSqlite(connectionString);
            return new BlogDbContext(builder.Options);
        }
    }
}
